package com.cloud.diffdemo.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.cloud.diffdemo.R
import com.cloud.diffdemo.callback.EasyDiffCallBack
import com.cloud.diffdemo.model.UserBean

/**
 * @auth: njb
 * @date: 2024/11/14 23:21
 * @desc: 用户信息适配器
 */
class UserAdapter(private val context: Context, private val userBean: MutableList<UserBean>): RecyclerView.Adapter<UserAdapter.UserViewHolder>() {
    private var userList:MutableList<UserBean> = ArrayList()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserViewHolder {
        val itemView = LayoutInflater.from(context).inflate(R.layout.item_user,parent,false)
        return UserViewHolder(itemView)
    }


    override fun getItemCount(): Int {
        return userBean.size ?: 0
    }

    override fun onBindViewHolder(holder: UserViewHolder, position: Int) {
        val name = userBean[position].name
        holder.tvName.text = name
    }


    var data: List<UserBean> = emptyList()
        set(value) {
            // 如果比较的集合较多(比如超过1000个), 建议使用子线程去比较
            val diffResult = DiffUtil.calculateDiff(EasyDiffCallBack(field, value))
            // 旧值赋新值
            field = value
            // 这里一定要保证在主线程调用
            diffResult.dispatchUpdatesTo(this)
        }

    /**
     * 刷新数据
     */
    fun notifyUpdate(userBean: MutableList<UserBean>){
        this.userList = userBean
        if(userBean.isEmpty()){
            this.userList = ArrayList()
        }
        notifyDataSetChanged()
    }

    /**
     * 使用Diff刷新数据
     */
    fun diffUpdate(newUserList: MutableList<UserBean>){
        val diffCallBack = EasyDiffCallBack(this.userBean,newUserList)
        val diffResult = DiffUtil.calculateDiff(diffCallBack)
        cloneData(newUserList)
        diffResult.dispatchUpdatesTo(UserAdapter(context,userBean))
    }

    private fun cloneData(newCoderList: MutableList<UserBean>) {
        this.userBean.clear()
        this.userBean.addAll(newCoderList)
    }

    inner class UserViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val tvName = itemView.findViewById<TextView>(R.id.tv_name)

    }
}